package com.quan.weixin.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.quan.common.base.bean.PageBean;
import com.quan.common.base.bean.ResultBean;
import com.quan.common.core.BaseController;
import com.quan.weixin.api.API;
import com.quan.weixin.common.WeixinContext;
import com.quan.weixin.common.WeixinUtil;
import com.quan.weixin.entity.WeixinNews;
import com.quan.weixin.model.BatchDeleteVo;
import com.quan.weixin.service.WeixinApiService;
import com.quan.weixin.service.WeixinNewsService;

@RestController
@RequestMapping(value = "/api/weixin/news")
public class WeixinNewsController extends BaseController {
	
	@Autowired
	private WeixinNewsService weixinNewsService;

	@Autowired
	private WeixinApiService weixinApiService;

	@PostMapping(value = "/add")
	public Object add(@Valid @RequestBody WeixinNews entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return ResultBean.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		
		JSONObject parseObject = addNews(entity) ;
		String mediaId = parseObject.getString("media_id") ;
		
		if(StringUtils.isNotBlank(mediaId)) {
			entity.setMediaId(mediaId);
			this.weixinNewsService.insertSelective(entity);
			return ResultBean.ok("图文素材添加成功");
		} else {
			logger.error("上传图文素材失败：{}", parseObject.toJSONString());
			return ResultBean.failure(parseObject.toJSONString());
		}

		
	}

	@GetMapping(value = "/delete/{id}/{mediaId}")
	public Object delete(@PathVariable Integer id, @PathVariable String mediaId) {
		this.weixinNewsService.deleteById(id);
		JSONObject deleteMedia = this.weixinApiService.deleteMedia(WeixinContext.getAccessToken(), mediaId) ;
		if(deleteMedia.getInteger("errcode") == 0) {
			return ResultBean.ok("删除图文素成功") ;
		} else {
			return ResultBean.failure("删除图文素失败"+deleteMedia.getString("errmsg")) ;
		}
	}
	
	@PostMapping(value = "/deleteBatch")
	public Object deleteBatch(@RequestBody BatchDeleteVo vo) {
		List<Integer> delIds = new ArrayList<Integer>() ;
		
		List<String> mediaIds = vo.getMediaIds();
		for(int i=0; i< mediaIds.size(); i++) {
			JSONObject deleteMedia = this.weixinApiService.deleteMedia(WeixinContext.getAccessToken(), mediaIds.get(i)) ;
			Integer errcode = deleteMedia.getInteger("errcode") ;
			if(errcode == 0) {
				delIds.add(vo.getIds().get(i)) ;
			}
		}
		
		if(!delIds.isEmpty()) {
			this.weixinNewsService.deleteByIds(StringUtils.join(delIds.toArray(), ",")) ;
			return ResultBean.ok("删除图文素成功，删除数量：[ "+delIds.size()+" ]") ;
		} else {
			return ResultBean.failure("删除图文素失败") ;
		}
	}

	@PostMapping(value = "/update")
	public Object update(@Valid @RequestBody WeixinNews entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return ResultBean.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		this.weixinNewsService.update(entity);
		return ResultBean.ok();
	}

	@GetMapping(value = "/get/{id}")
	public Object list(@PathVariable Integer id) {
		return this.weixinNewsService.selectOneById(id);
	}
	
	@GetMapping(value = "/list")
	public Object list(WeixinNews entity) {
		return ResultBean.ok(this.weixinNewsService.selectPage(entity, new PageBean(request)));
	}
	
	/**
	 * 新增图文素材
	 * @param entity
	 * @return
	 */
	private JSONObject addNews(WeixinNews entity) {
		String addNewsUrl = API.get(API.ADD_NEWS_URL, WeixinContext.getAccessToken()) ;
		
		Map<String, Object> artilces = new HashMap<String, Object>() ;
		List<Object> list = new ArrayList<Object>() ;
		LinkedHashMap<String, Object> addNewsMap = new LinkedHashMap<String, Object>() ;
		addNewsMap.put("title", entity.getTitle()) ;
		addNewsMap.put("thumb_media_id", entity.getThumbMediaId()) ;
		addNewsMap.put("author", entity.getAuthod()) ;
		addNewsMap.put("digest", entity.getDigest()) ;
		addNewsMap.put("show_cover_pic", entity.getShowCoverPic()) ;
		addNewsMap.put("content", entity.getContent()) ;
		addNewsMap.put("content_source_url", "www.qq.com") ;
		addNewsMap.put("need_open_comment", entity.getNeedOpenComment()) ;
		addNewsMap.put("only_fans_can_comment", entity.getOnlyFansCanComment()) ;
		list.add(addNewsMap) ;
		artilces.put("articles", list);
		
		return WeixinUtil.doPostJSON(addNewsUrl, artilces) ;
	}
	
}
